﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Trentacular.SharePoint.Util;
using Trentacular.SharePoint.Web.UI.WebControls;

namespace Trentacular.SharePoint.Layouts
{
    public partial class SitePropertiesEditor : LayoutsPageBase
    {
        protected override bool RequireSiteAdministrator { get { return true; } }

        private bool DataBindNeeded = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                gvProperties.Sort("Key", SortDirection.Ascending);
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (DataBindNeeded)
                gvProperties.DataBind();
        }

        protected void GetProperties(DelegateSelectArguments args)
        {
            args.Results = Web.AllProperties.Cast<DictionaryEntry>().Select(de =>
                new KeyValuePair<string, string>(de.Key.ToString(), de.Value.ToString()));
        }

        protected void UpdateProperty(DelegateUpdateArguments args)
        {
            var key = (string)args.Keys["Key"];
            var value = (string)args.Values["Value"];
            var oldValue = (string)args.OldValues["Value"];

            if (value == oldValue)
            {
                args.ResultCount = 0;
                return;
            }

            Web.AddPropertyAndUpdate(key, value);

            DataBindNeeded = true;
            args.ResultCount = 1;
        }

        protected void DeleteProperty(DelegateDeleteArguments args)
        {
            var key = (string)args.Keys["Key"];

            Web.RemovePropertyAndUpdate(key);

            DataBindNeeded = true;
            args.ResultCount = 1;
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            var key = txtKey.Text;
            var value = txtValue.Text;

            Web.AddPropertyAndUpdate(key, value);

            txtKey.Text = null;
            txtValue.Text = null;

            DataBindNeeded = true;
        }
    }
}
